using System;
using System.Text;
using System.Collections.Generic;
using InfoJetSoft.Service.XPath;

//CID 0164 //2008.12.13 //Begin
namespace InfoJetSoft.Service.XPath.Exprs
{
	/// <summary>
	/// Summary description for FilterExpr.
	/// </summary>
    public class FilterExpr : IExpr
	{
		private IExpr _primary = null;
        private List<IExpr> _predicateList = null;

		public FilterExpr()
		{
			//
			// TODO: Add constructor logic here
			//
        }

        public IExpr Primary
        {
            get
            {
                return this._primary;
            }
        }

        public List<IExpr> Predicates
        {
            get
            {
                return this._predicateList;
            }
        }

        public object Evaluate(ExprContext context)
        {
            //CID 0823 //2011.03.03 //Begin
            object result = this._primary.Evaluate(context);
            if (this._predicateList.Count > 0)
            {
                result = Step.FilterPredicates(context, result, this._predicateList);
            }
            return result;
            //CID 0823 //2011.03.03 //End
        }

        //CID 0866 //2011.04.01 //Begin
        public void Visit(IExprVisitor visitor)
        {
            this._primary.Visit(visitor);
            foreach (IExpr predicateExpr in this._predicateList)
            {
                predicateExpr.Visit(visitor);
            }
        }
        //CID 0866 //2011.04.01 //End

        public void Print(StringBuilder buffer)
        {
            this._primary.Print(buffer);
            foreach (IExpr expr in this._predicateList)
            {
                buffer.Append("[");
                expr.Print(buffer);
                buffer.Append("]");
            }
        }

		public static IExpr Parse( ExprParser parser )
		{
			IExpr primary = PrimaryExpr.Parse( parser );
			if( primary == null )
			{
				return null;
			}

            List<IExpr> predicateList = new List<IExpr>();
            IExpr predicate = Predicate.Parse(parser);
			while( predicate != null )
			{
                predicateList.Add(predicate);
				predicate = Predicate.Parse( parser );
			}

            if (predicateList.Count > 0)
            {
                FilterExpr filterExpr = new FilterExpr();
                filterExpr._primary = primary;
                filterExpr._predicateList = predicateList;
                return filterExpr;
            }
            else
            {
                return primary;
            }
		}
	}
}
//CID 0164 //2008.12.13 //End
